import re
import uuid

from rest_framework import serializers
from django.conf import settings
from rest_framework.fields import SerializerMethodField
from rest_framework_jwt.settings import api_settings
# from itsdangerous import TimedJSONWebSignatureSerializer as TJS
import hashlib
from mini_api.models import PcDevice, Company, Process, User, Job
import base64


class PcDeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = PcDevice
        fields = '__all__'
        extra_kwargs = {
            "machine_code": {"required": False}
        }
        # exclude = ('machine_code',)

    def create(self, validated_data):
        machine_code = uuid.uuid4()
        validated_data['machine_code'] = machine_code
        pc_device = PcDevice.objects.create(**validated_data)
        return pc_device


class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = '__all__'


class ProcessSerializer(serializers.ModelSerializer):
    # machine_code = serializers.ReadOnlyField(source='pcdevice.machine_code')
    pc_device_detail = serializers.SerializerMethodField()
    class Meta:
        model = Process
        fields = '__all__'
    def get_pc_device_detail(self,obj):
        pc_device_set = obj.pcdevice
        # tjs = TJS(settings.SECRET_KEY)
        # machine_code_token = tjs.dumps(pc_device_set.machine_code).decode()
        machine_code_base64 = base64.b64encode(pc_device_set.machine_code.encode('utf8'))
        return {'pc_id':pc_device_set.id,'machine_code':machine_code_base64,'host_name':pc_device_set.host_name}


class RPAUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    token = serializers.CharField(read_only=True)
    wechat_id = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username', 'mobile', 'password', 'password2', 'id', 'wechat_id', 'token', 'company')
        extra_kwargs = {
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            },
            'username': {
                'max_length': 20,
                'min_length': 5,
            },

        }

    # 验证手机号格式
    def validate_mobile(self, value):

        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate(self, attrs):

        # username是手机号格式
        if re.match(r'^1[3-9]\d{9}$', attrs['username']):
            # 验证手机号和用户名名是否一致
            if attrs['mobile'] != attrs['username']:
                raise serializers.ValidationError('手机号和用户名不一致')

        # 密码验证
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('密码不一致')
        return attrs

    def create(self, validated_data):

        # 删除不需要的字段数据
        del validated_data['password2']

        # 保存用户对象
        validated_data['wechat_id'] = uuid.uuid4()
        user = User.objects.create_user(**validated_data)

        # 生成JWT token值
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 在user对象中添加token属性
        user.token = token
        user.wechat_id = validated_data['wechat_id']
        return user

class ProcessCMDSerializer(serializers.Serializer):
    machine_code_token = serializers.CharField(max_length=128,required=True)
    process_id = serializers.CharField(max_length=128,required = True)

    def validate_process_id(self,value):
        try:
            process_data = Process.objects.get(id = value)
        except Exception as e:
            print(e)

            raise serializers.ValidationError('流程参数出错')

        return process_data

    def validate_machine_code_token(self,value):
        token_de = base64.b64decode(value).decode('utf8')
        try:
            pc_device = PcDevice.objects.get(machine_code = token_de)
        except Exception as e:
            print(e)
            raise serializers.ValidationError("PC参数出错")
        return pc_device

class JobListSerializer(serializers.ModelSerializer):
    process_detail = SerializerMethodField()
    class Meta:
        model = Job
        fields = '__all__'


    def get_process_detail(self,obj):
        process_obj = obj.process
        return {"process_id":process_obj.id,"process_name":process_obj.process_name,"pc_id":process_obj.pcdevice.id,"machine_code":process_obj.pcdevice.machine_code}

